package com.qf.push.controller;


import com.qf.base.result.R;
import com.qf.push.dto.MessageDTO;
import com.qf.push.model.Message;
import com.qf.push.server.WebSocketServer;
import com.qf.push.service.PushService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author 30909
 */
@RestController
@RequestMapping("qf/push")
public class WebPushController {

    @Resource
    private WebSocketServer webSocketServer;
    @Resource
    private PushService pushService;


    @PostMapping("web")
    public R sendWeb(@RequestBody MessageDTO messageDTO) {
        Long uid = messageDTO.getUid();
        String message = messageDTO.getMessage();
        Integer serviceId = messageDTO.getServiceId();
        Long requestId = messageDTO.getRequestId();
        // 推送之前，先判断是否保存过，如果保存过，就返回处理完成
        if (pushService.isIdem(requestId)){
            return  R.ok("已经处理完成");
        }

        boolean result = webSocketServer.sendInfo(uid + "", message);
        Message msg = new Message();
        msg.setUid(uid);
        msg.setContent(message);
        msg.setServiceId(serviceId);
        if (result) {
            //往数据库里存 state = 1
            msg.setState(1);
            pushService.saveMessage(msg,requestId);
            return R.ok("推送完成");
        } else {
            //往数据库里存 state  = 0
            msg.setState(0);
            pushService.saveMessage(msg,requestId);
            return R.ok("推送任务已经设置");
        }

    }

}
